package com.jifeng.httporhttps;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


 

import android.util.Log;

/**
 * 采用httpURLConnection连接方式区请求网络数据
 * 
 * @author Administrator
 * 
 */
public class HttpUtil {
	/**
	 *  Https （POST）
	 */
	//, String name, String pwd, String code
	public static String getReultForHttpPost(String path) throws ClientProtocolException,
			IOException {
		HttpURLConnection http = null;
		URL url; 
		url = new URL(path);
		// 判断是http请求还是https请求
		if (url.getProtocol().toLowerCase().equals("https")) {
			trustAllHosts();
			http = (HttpsURLConnection) url.openConnection();
			((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认
		} else {
			http = (HttpURLConnection) url.openConnection();
		}
		http.setConnectTimeout(5000);// 设置超时时间
		http.setReadTimeout(2000);
		http.setRequestMethod("POST");// 设置请求类型为post
		http.setDoInput(true);
		http.setDoOutput(true); 
		//getCookie(http);
//		 byte [] entity=("username="+URLEncoder.encode(name,"utf-8")+
//			        "&password="+URLEncoder.encode(pwd,"utf-8")+
//			        "&loginstyle="+URLEncoder.encode("morden","utf-8")+
//			        "&code="+URLEncoder.encode(code,"utf-8")
//			 ).getBytes();
		http.setRequestProperty("Cookie", Constract.cookie);
//		http.setRequestProperty("Charset", "UTF-8");
//		http.setRequestProperty("Content-Length", String.valueOf(entity.length));
//		http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

//		DataOutputStream out = new DataOutputStream(http.getOutputStream());
//		out.write(entity);
//		out.flush();
//		out.close();
		 
	//	obj.setHttpStatus(http.getResponseCode());// 设置http返回状态200还是403
		BufferedReader in = null;
		if (http.getResponseCode() == 200) {
			//getCookie(http);
			in = new BufferedReader(new InputStreamReader(http.getInputStream()));
			 
		} else{
			in = new BufferedReader(new InputStreamReader(http.getErrorStream()));
		}
		String result="";
		String line="";
		while((line=in.readLine())!=null){
			result+=line; // 得到返回结果
		}
	
		 
		in.close();
		http.disconnect();

		return result;
	}

	
	
	/** 得到cookie */
	public static void getCookie(HttpURLConnection http) {
		String cookieVal = null;
		String key = null;
		Constract.cookie = "";//全局变量
		for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {
			if (key.equalsIgnoreCase("set-cookie")) {
				cookieVal = http.getHeaderField(i);
				cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
				Constract.cookie = Constract.cookie + cookieVal+ ";";
			}
		}
		//Log.i("11111", Constract.cookie);
	}
	
	static TrustManager[] xtmArray = new MytmArray[] { new MytmArray() };

	/**
	 * 信任所有主机-对于任何证书都不做检查
	 */
	public static void trustAllHosts() {
		// Create a trust manager that does not validate certificate chains
		// Android 采用X509的证书信息机制
		// Install the all-trusting trust manager
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, xtmArray, new java.security.SecureRandom());
			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
			// HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);//
			// 不进行主机名确认
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			// TODO Auto-generated method stub
			// System.out.println("Warning: URL Host: " + hostname + " vs. "
			// + session.getPeerHost());
			return true;
		}
	};
	public static String timeOut(String path) {
		String result = null;
		HttpURLConnection http = null;
		URL url;
		try {
			url = new URL(path);
			
			// 判断是http请求还是https请求
			if (url.getProtocol().toLowerCase().equals("https")) {
				HttpUtil.trustAllHosts();
				http = (HttpsURLConnection) url.openConnection();
				((HttpsURLConnection) http)
						.setHostnameVerifier(HttpUtil.DO_NOT_VERIFY);// 不进行主机名确认
			} else {
				http = (HttpURLConnection) url.openConnection();
			}

			http.setConnectTimeout(3500);// 设置超时时间
		//	http.setReadTimeout(2000);
			http.setRequestMethod("POST");// 设置请求类型为post
			http.setDoInput(true);
			 
			http.setDoOutput(true);
			BufferedReader in;
			if (http.getResponseCode() == 200) {
				result="qwwwwwwewqewqewqewqe";
			} else {
				result=null;
			} 
			if (http != null)
				http.disconnect();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	
	public static String executePost(String path) {
		String result = null;
		HttpURLConnection http = null;
		URL url;
		try {
			url = new URL(path);
			
			// 判断是http请求还是https请求
			if (url.getProtocol().toLowerCase().equals("https")) {
				HttpUtil.trustAllHosts();
				http = (HttpsURLConnection) url.openConnection();
				((HttpsURLConnection) http)
						.setHostnameVerifier(HttpUtil.DO_NOT_VERIFY);// 不进行主机名确认
			} else {
				http = (HttpURLConnection) url.openConnection();
			}

			http.setConnectTimeout(3500);// 设置超时时间
		//	http.setReadTimeout(2000);
			http.setRequestMethod("POST");// 设置请求类型为post
			http.setDoInput(true);
			 
			http.setDoOutput(true);
			BufferedReader in;
			if (http.getResponseCode() == 200) {
				in = new BufferedReader(new InputStreamReader(
						http.getInputStream(),"GBK"));
			} else {
				in = new BufferedReader(new InputStreamReader(
						http.getErrorStream()));
			}
			  
			String line = "";
			while ((line = in.readLine()) != null) {
				result += line; // 得到返回结果
			}
		//	Log.i("11111", result);
			in.close();
			if (http != null)
				http.disconnect();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	
	
	@SuppressWarnings("unused")
	public static String executePost(String path,String Cookiestr) {
		String result = null;
		HttpURLConnection http = null;
		URL url;
		try {
			url = new URL(path);
			
			// 判断是http请求还是https请求
			if (url.getProtocol().toLowerCase().equals("https")) {
				HttpUtil.trustAllHosts();
				http = (HttpsURLConnection) url.openConnection();
				((HttpsURLConnection) http)
						.setHostnameVerifier(HttpUtil.DO_NOT_VERIFY);// 不进行主机名确认
			} else {
				http = (HttpURLConnection) url.openConnection();
			}

			http.setConnectTimeout(5000);// 设置超时时间
			//http.setReadTimeout(2000);
			http.setRequestMethod("POST");// 设置请求类型为post
			http.setDoInput(true);
			http.setRequestProperty("Cookie", Cookiestr);
			http.setDoOutput(true);
		 
			BufferedReader in;
			int num=http.getResponseCode();
			if (http.getResponseCode() == 200) {
				in = new BufferedReader(new InputStreamReader(
						http.getInputStream(),"GB2312"));
			} else {
				in = new BufferedReader(new InputStreamReader(
						http.getErrorStream()));
			}
			  
			String line = "";
			while ((line = in.readLine()) != null) {
				result += line; // 得到返回结果
			}
		//	Log.i("11111", result);
			in.close();
			if (http != null)
				http.disconnect();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	

	/**
	 * 采用HttpClient请求方式（GET）
	 */
	public static byte[] httpClientGet(String path) {
		byte[] data = null;

		try {
			// 构造实例httpClientGet的类DefaultHttpClient
			// 获取连接
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);
			// 执行连接（get请求）
			// 返回封装类HttpResponse
			HttpResponse response = client.execute(get);
			// 获得返回码(比如：code码，=200表示成功连接)头协议，数据
			if (response.getStatusLine().getStatusCode() == 200) { 
				HttpEntity entity = response.getEntity();
				// entity.getContent()获取InputStream
				// 通过EntityUtils将entity内容转换成byte[]
				data = EntityUtils.toByteArray(entity);

			} else {
				// 不同的返回自己具体处理
				// Log.i("Code", "http code"
				// + response.getStatusLine().getStatusCode());
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
}
